package ar.com.lemil.bb.http.detection;

import java.util.Hashtable;

import net.rim.blackberry.api.browser.Browser;
import net.rim.device.api.servicebook.ServiceBook;
import net.rim.device.api.servicebook.ServiceRecord;
import net.rim.device.api.system.RadioInfo;
import net.rim.device.api.system.WLANInfo;

public class BlackberryConnections {

	public static final String DIRECT_CONN 	= "Direct";
	public static final String PLAIN_CONN 	= "Auto";
	public static final String CARRIER_CONN = "Carrier";
	public static final String WAP2_CONN 	= "BrowserWAP";
	public static final String IWAP_CONN 	= "Browser";
	public static final String BESMDS_CONN 	= "BES/MDS";
	public static final String BIS_B_CONNN 	= "BIS-B";
	public static final String WIFI_CONNN 	= "WIFI";
	public static final String WIFI2_CONNN 	= "WIFI-IPPP";
	public static final String WIFI3_CONNN 	= "WIFI-WPTCP";
	
	public static final String[] CONN_PLAN = { WIFI_CONNN, WIFI2_CONNN, WIFI3_CONNN, BIS_B_CONNN, BESMDS_CONN, DIRECT_CONN, IWAP_CONN, CARRIER_CONN, WAP2_CONN , PLAIN_CONN};

	public static final String[] HTTP_POSTFIXES = { "", ";deviceside=false",
			";deviceside=false;ConnectionType=mds-public", ";deviceside=true",
			";deviceside=true;interface=wifi",
			";WapGatewayAPN=proxy;WapGatewayIP=10.250.250.250" };


	public static final String CARRIER_PERSONAL = "Personal";
	public static final String CARRIER_CLARO_AR = "Claro AR";
	public static final String CARRIER_MOVISTAR = "Movistar";
	public static final String CARRIER_SIMULATOR = "RIM Simulator";
	
	public static final String[] HTTP_WAP_CARRIERS = {CARRIER_PERSONAL, CARRIER_CLARO_AR, CARRIER_MOVISTAR};
		
	private static Hashtable getCarrierSettings(){
	
		Hashtable t = new Hashtable();
		t.put(CARRIER_PERSONAL,";WAPGatewayAPN=gprs.personal.com;WAPGatewayIP=172.16.0.20;WAPGatewayPort=9201;TunnelAuthUsername=gprs;TunnelAuthPassword=adgj;deviceside=true");
		t.put(CARRIER_CLARO_AR,";WAPGatewayAPN=igprs.claro.com.ar;WAPGatewayIP=170.51.255.240;WAPGatewayPort=8080;TunnelAuthUsername=clarogprs;TunnelAuthPassword=clarogprs999;deviceside=true");
		t.put(CARRIER_MOVISTAR,";WAPGatewayAPN=wap.gprs.unifon.com.ar;WAPGatewayIP=200.5.68.10;WAPGatewayPort=8080;TunnelAuthUsername=wap;TunnelAuthPassword=wap;deviceside=true");
		t.put(CARRIER_SIMULATOR,";WAPGatewayAPN=rim.net.gprs;WAPGatewayIP=127.0.0.1;deviceside=true");
		return t;
	}
	
	public static final Hashtable HTTP_WAP_CARRIERS_SETTINGS = getCarrierSettings();
	

	
	private static BlackberryConnections instance = new BlackberryConnections();
	
	public static BlackberryConnections getInstance(){
		return instance;
	}
	
	private BlackberryConnections(){
		
	}
	
	public Hashtable getFromHints(){
		
		Hashtable postfixes = new Hashtable();
		//
		//Logger.getInstance().log("Direct Added");
		postfixes.put(DIRECT_CONN, HTTP_POSTFIXES[3]);

		//
		//Logger.getInstance().log("Plain Added");
		postfixes.put(PLAIN_CONN, "");
		
		//BES/MDS
		//Logger.getInstance().log("BES/MDS Added");
		String bes =  HTTP_POSTFIXES[1];
		postfixes.put(BESMDS_CONN,bes);
		
		return postfixes;
	}
	
	
	public Hashtable getFromActiveSB() {

		Hashtable postfixes = new Hashtable();

		try {
			//Logger.getInstance().log("Getting SB");
			ServiceBook sb = ServiceBook.getSB();
			// IPPP
			//Logger.getInstance().log("Find records IPPP");
			ServiceRecord[] recs = sb.findRecordsByCid("IPPP");
			
			if (recs != null && recs.length != 0) {
				boolean encmode = false;
				int len = recs.length;
				for (int i = 0; i < len; i++) {
					ServiceRecord sr = recs[i];
					if (!sr.isValid() || sr.isDisabled())
						continue;
					String name = sr.getName().trim();
					if (sr.getEncryptionMode() == 2) {
						encmode = true;
						continue;
					}
					if (name != null){
							if(name.startsWith("IPPP for BIBS")
									|| name.indexOf("BISB") > -1
									|| name.indexOf("BIS-B") > -1
									|| name.startsWith("BISB")
									|| name.startsWith("BIS-B")
									|| name.startsWith("Internet")
									|| name.startsWith("IPPP")	){
							//Logger.getInstance().log("BIS-B Added");
							String bisb = HTTP_POSTFIXES[2] + "ConnectionUID=" + sr.getUid() + ";";
							postfixes.put(BIS_B_CONNN, bisb );
						}
					}
				}
			}

			// BROWSER APN
			//Logger.getInstance().log("Searching for " + Browser.CID_BROWSERCONFIG);
			ServiceRecord[] recs2 = sb
					.findRecordsByCid(Browser.CID_BROWSERCONFIG);
			
			if (recs2 != null && recs2.length != 0) {
			    int len = recs2.length;
			    for (int i = 0; i < len; i++) {
					ServiceRecord sr = recs2[i];
					
					if (!sr.isValid() || sr.isDisabled()){
						continue;
					}

					String na = sr.getName().toLowerCase();
					if (na.indexOf("wifi") > -1
							|| na.indexOf("wi-fi") > -1  ) {
						String uid = ";deviceside=true;ConnectionUID=" + sr.getUid() + ";";
						//Logger.getInstance().log("WIFI-B Added");
						postfixes.put(WIFI2_CONNN, uid);
						continue;
					}
					
					String transportUID_B = Browser.getTransportUid(sr);
					ServiceRecord[] recs3 = sb.findRecordsByUid(transportUID_B);
					int len2 = recs3.length;
					for (int l = 0; l < len2; l++) {
						if(recs3[l].getAPN() != null){
							String s1 = ";WapGatewayAPN=" + recs3[l].getAPN() + ";";
							s1 = s1.toLowerCase();
							
							String settings1 = (String)HTTP_WAP_CARRIERS_SETTINGS.get(CARRIER_PERSONAL);
							if (settings1.toLowerCase().indexOf(s1) > -1 ){
								postfixes.put(IWAP_CONN, settings1);
							}
							settings1 = (String)HTTP_WAP_CARRIERS_SETTINGS.get(CARRIER_CLARO_AR);
							if (settings1.toLowerCase().indexOf(s1) > -1 ){
								postfixes.put(IWAP_CONN, settings1);
							}
							
							settings1 = (String)HTTP_WAP_CARRIERS_SETTINGS.get(CARRIER_MOVISTAR);
							if (settings1.toLowerCase().indexOf(s1) > -1 ){
								postfixes.put(IWAP_CONN, settings1);
							}
						} 
					}
				}
			}
			
			//WAP2
			ServiceRecord[] records = sb.findRecordsByCid("WPTCP");
			for (int i = 0; i < records.length; i++) {
				if (records[i].isValid() && !records[i].isDisabled()) {
					if (records[i].getUid() != null
							&& records[i].getUid().length() != 0) {
						if (records[i].getUid().toLowerCase().indexOf("wifi") > -1 
								|| records[i].getUid().toLowerCase().indexOf("wi-fi") > -1 ) {
							String uid = ";deviceside=true;ConnectionUID=" + records[i].getUid() + ";";
							//Logger.getInstance().log("WIFI2 Added");
							postfixes.put(WIFI3_CONNN, uid);
						}

						if ((records[i].getUid().toLowerCase().indexOf("wifi") == -1)
								&& (records[i].getUid().toLowerCase().indexOf(
										"mms") == -1)) {
							String uid = ";ConnectionUID=" + records[i].getUid() + ";";
							postfixes.put(WAP2_CONN, uid);
							//Logger.getInstance().log("WAP2 Added");
						}	
					}
				}
			}
			
			
			//
			//WIFI
			if ( (WLANInfo.getWLANState() == WLANInfo.WLAN_STATE_CONNECTED) &&
				      RadioInfo.areWAFsSupported(RadioInfo.WAF_WLAN)) {
				//Logger.getInstance().log("WIFI Added");
				postfixes.put("WIFI", HTTP_POSTFIXES[4]);
			}

			return postfixes;

		} catch (Exception ex) {
			throw new RuntimeException("Error detectando conectividad");
		}
	}

}
